import { useEffect, useRef, useState, RefObject } from 'react'

interface UseLoadMoreOptions {
  hasMore: boolean
  containerRef: RefObject<HTMLElement>
}

export function useLoadMore(
  loadMore: () => Promise<void>,
  { hasMore, containerRef }: UseLoadMoreOptions
) {
  const topRef = useRef<HTMLDivElement>(null)
  const [isFetching, setIsFetching] = useState(false)
  const [isTopVisible, setIsTopVisible] = useState(false)

  useEffect(() => {
    if (!containerRef.current || !topRef.current) return

    const observer = new IntersectionObserver(
      async ([entry]) => {
        const isVisible = entry.isIntersecting
        setIsTopVisible(isVisible)

        if (isVisible && hasMore && !isFetching) {
          setIsFetching(true)

          // 记录滚动前的位置
          const prevScrollHeight = containerRef.current?.scrollHeight || 0

          try {
            await loadMore()

            // 等待 DOM 渲染完再处理滚动位置
            setTimeout(() => {
              if (containerRef.current) {
                const newScrollHeight = containerRef.current.scrollHeight
                containerRef.current.scrollTop =
                  newScrollHeight - prevScrollHeight
              }
            }, 0)
          } catch (e) {
            console.error('LoadMore failed:', e)
          } finally {
            setIsFetching(false)
          }
        }
      },
      {
        root: containerRef.current,
        threshold: 1.0,
      }
    )

    observer.observe(topRef.current)

    return () => observer.disconnect()
  }, [containerRef, hasMore, isFetching, loadMore])

  return { topRef, isTopVisible, isFetching }
}
